﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ArbabTravelsERP.Models;

namespace LMS.Controllers
{
    //[ErrorFilterAttribute]
    //[ActivityLogAttribiute]
    //[AuthenticateUserAttribute]
    public class MenuController : Controller
    {
        DataAccessLayer.Menu_DAL objMenu_DAL = new DataAccessLayer.Menu_DAL(); //Creating object of DBdata
        All_Master master = new All_Master();

        #region Get List and Add Menu
        // GET: /Menu/
        public ActionResult Index(string ID, string btnReset)
        {
            ArbabTravelsERP.Models.MENU objMenu = new ArbabTravelsERP.Models.MENU();
            ViewData["IS_PARENT"] = _GetBoolValue();
            if (ID == null)
            {
                objMenu.IS_PARENT = true;
                ViewBag.SubTitle = "Parent Menu";
                objMenu.MenuDS = objMenu_DAL.GetMenu("1", "", "", "Parent");
            }
            else
            {
                objMenu.IS_PARENT = false;
                objMenu.MenuDS = objMenu_DAL.GetMenu("0", ID, "", "Child");
                if (objMenu.MenuDS.Tables[0].Rows.Count > 0)
                    ViewBag.SubTitle = "Child Menu " + objMenu.MenuDS.Tables[0].Rows[0]["PARENT_MENU_NAME"].ToString();
                else
                    ViewBag.SubTitle = "Child Menu";
            }
            
            return View(objMenu);
        }

        public List<SelectListItem> _GetBoolValue()
        {
            List<SelectListItem> li = new List<SelectListItem>();
            li.Add(new SelectListItem { Text = "False", Value = "false" });
            li.Add(new SelectListItem { Text = "True", Value = "true" });
            return li;
        }

        // POST: /Menu/Create
        [HttpPost]
        public ActionResult Index(FormCollection collection, ArbabTravelsERP.Models.MENU objMENU, string ID)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (ID == null)
                        objMENU.IS_PARENT = true;

                    string result = objMenu_DAL.AddMenu(objMENU.MENU_NAME, objMENU.MENU_TITLE, objMENU.PAGE_NAME, objMENU.CONTROLLER_NAME, ID, Convert.ToBoolean(objMENU.IS_PARENT), objMENU.REMARK, "", "Add");
                    if (result == "1")
                    {
                        ViewBag.Success = "Menu inserted successfully";
                    }
                    return RedirectToAction("Index", "Menu", new { ID = ID });
                }
                else
                {
                    ViewBag.Error = "Please fill mandatory data";
                    ViewData["IS_PARENT"] = _GetBoolValue();

                    if (ID == null)
                    {
                        objMENU.IS_PARENT = true;
                        ViewBag.SubTitle = "Parent Menu";
                        objMENU.MenuDS = objMenu_DAL.GetMenu("1", "", "", "Parent");
                    }
                    else
                    {
                        objMENU.IS_PARENT = false;
                        objMENU.MenuDS = objMenu_DAL.GetMenu("0", ID, "", "Child");
                        if (objMENU.MenuDS.Tables[0].Rows.Count > 0)
                            ViewBag.SubTitle = "Child Menu " + objMENU.MenuDS.Tables[0].Rows[0]["PARENT_MENU_NAME"].ToString();
                        else
                            ViewBag.SubTitle = "Child Menu";
                    }
                    return View(objMENU);
                }
            }
            catch
            {
                return View();
            }
        }
        #endregion

        #region Edit menu
        // GET: /Menu/Edit/5
        public ActionResult Edit(string id)
        {
            return MenuDetails_By_MenuID(id);
        }

        private ActionResult MenuDetails_By_MenuID(string id)
        {
            ArbabTravelsERP.Models.MENU objMenu = new ArbabTravelsERP.Models.MENU();
            DataSet dsMenu = objMenu_DAL.GetMenu("", "", id, "Child");

            ViewData["IS_PARENT"] = _GetBoolValue();
            objMenu.PARENT_MENU_NAME = dsMenu.Tables[0].Rows[0]["PARENT_MENU_NAME"].ToString();
            objMenu.MENU_NAME = dsMenu.Tables[0].Rows[0]["MENU_NAME"].ToString();
            objMenu.PARENT_MENU_ID = dsMenu.Tables[0].Rows[0]["PARENT_MENU_ID"].ToString();
            objMenu.MENU_TITLE = dsMenu.Tables[0].Rows[0]["MENU_TITLE"].ToString();
            objMenu.PAGE_NAME = dsMenu.Tables[0].Rows[0]["PAGE_NAME"].ToString();
            objMenu.CONTROLLER_NAME = dsMenu.Tables[0].Rows[0]["CONTROLLER_NAME"].ToString();
            objMenu.IS_PARENT = Convert.ToBoolean(dsMenu.Tables[0].Rows[0]["IS_PARENT"].ToString());
            objMenu.REMARK = dsMenu.Tables[0].Rows[0]["REMARK"].ToString();

            return View(objMenu);
        }

        //
        // POST: /Menu/Edit/5
        [HttpPost]
        public ActionResult Edit(string id, FormCollection collection, ArbabTravelsERP.Models.MENU objMENU)
        {
            try
            {
                // TODO: Add update logic here                
                if (ModelState.IsValid)
                {
                    string result = objMenu_DAL.AddMenu(objMENU.MENU_NAME, objMENU.MENU_TITLE, objMENU.PAGE_NAME, objMENU.CONTROLLER_NAME, objMENU.PARENT_MENU_ID, Convert.ToBoolean(objMENU.IS_PARENT), objMENU.REMARK, id, "Edit");
                    if (result == "1")
                        ViewBag.Success = "Menu Updated successfully";

                    return RedirectToAction("Index", "Menu", new { ID = objMENU.PARENT_MENU_ID });
                }
                else
                {
                    ViewBag.Error = "Please insert proper data";
                    return MenuDetails_By_MenuID(id);
                }
            }
            catch
            {
                return MenuDetails_By_MenuID(id);
            }
        }

        #endregion

        #region Delete Menu
        // GET: /Menu/Delete/5
        public ActionResult Delete(string id)
        {
            return MenuDetails_By_MenuID(id);
        }

        // POST: /Menu/Delete/5
        [HttpPost]
        public ActionResult Delete(string id, FormCollection collection, ArbabTravelsERP.Models.MENU objMENU)
        {
            try
            {
                // TODO: Add delete logic here                
                if (ModelState.IsValid)
                {
                    string result = objMenu_DAL.AddMenu(objMENU.MENU_NAME, objMENU.MENU_TITLE, objMENU.PAGE_NAME, objMENU.CONTROLLER_NAME, objMENU.PARENT_MENU_ID, Convert.ToBoolean(objMENU.IS_PARENT), objMENU.REMARK, id, "Delete");
                    if (result == "1" || result == "2")
                    {
                        ViewBag.Success = "Menu Deleted successfully";
                        return RedirectToAction("Index", "Menu", new { ID = objMENU.PARENT_MENU_ID });
                    }
                    else
                    {
                        ViewBag.Error = "Record can not be deleted because it is used by another user.";
                        return MenuDetails_By_MenuID(id);
                    }
                }
                else
                {
                    ViewBag.Error = "Record can not be deleted because it is used by another user.";
                    return MenuDetails_By_MenuID(id);
                }
            }
            catch
            {
                return MenuDetails_By_MenuID(id);
            }
        }
        #endregion

        #region Mapping Menu to User Type
        //GET:
        public ActionResult MenuMapping(string id, string btnGetMenu)
        {
            
            ViewData["GetUserType"] = master.GetUserType(); //Bind User Type
            return View();
        }

        //POST :
        [HttpPost]
        public ActionResult MenuMapping(FormCollection FM, string btnGetMenu, string CHANNEL_CODE, string USER_TYPE_ID)
        {
            ViewData["GetUserType"] = master.GetUserType();//Bind User Type
            if (USER_TYPE_ID != "")
            {
                int user_type_id = Convert.ToInt32(Request.Form["USER_TYPE_ID"]);
                var hdnrowcount = Request.Form["hdnrowcount"];
                string Created_By = "ambi";
                string result;
                bool menuselectedval;
                for (int i = 0; i <= Convert.ToInt32(hdnrowcount); i++)
                {
                    int Menu_ID = Convert.ToInt32(Request.Form["hdnMenu_ID" + i]);
                    var menuselected = Request.Form["chksel" + i];

                    if (menuselected == "on")
                        menuselectedval = true;
                    else
                        menuselectedval = false;

                    if (menuselectedval == true)
                        result = objMenu_DAL.MenuInsertionByUserType(user_type_id, Menu_ID, Created_By, "Add");
                    else
                        result = objMenu_DAL.MenuInsertionByUserType(user_type_id, Menu_ID, Created_By, "Del");
                }

                ViewBag.Success = "Menu assigned selected user type successfully";
            }
            else
                ViewBag.Error = "Please select mandatory fields.";

            return View();
        }
        #endregion

        #region Methods
        //DataAccessLayer.Channel_Master_DAL objChnl = new DataAccessLayer.Channel_Master_DAL(); //calling class DBdata
        //Fetch all channel for Channel Drop Down
        //public SelectList GetChannel()
        //{
        //    string MANAGER_CODE = ((DataTable)Session["UserDetails"]).Rows[0]["User_SapCode"].ToString();
        //    if (System.Web.HttpContext.Current.Cache["dtChannelMapping"] == null)
        //        System.Web.HttpContext.Current.Cache["dtChannelMapping"] = objChnl.ChannelDatabyHOUser(MANAGER_CODE).Tables[0];

        //    DataTable dtChanl = objChnl.ChannelDatabyHOUser(MANAGER_CODE).Tables[0];

        //    if (dtChanl.Rows.Count > 0)
        //    {
        //        //DataTable dtState = ((DataTable)System.Web.HttpContext.Current.Cache["dtChannelMapping"]).DefaultView.ToTable(true, new string[] { "CHANNEL_CODE", "CHANNEL_NAME" });
        //        DataTable dtState = dtChanl.DefaultView.ToTable(true, new string[] { "CHANNEL_CODE", "CHANNEL_NAME" });
        //        var results = from row in dtState.AsEnumerable()
        //                      select new
        //                      {
        //                          Value = row.Field<string>("CHANNEL_CODE"),
        //                          Text = row.Field<string>("CHANNEL_NAME")
        //                      };
        //        return new SelectList(results, "Value", "Text");
        //    }
        //    else
        //        return new SelectList("", "Value", "Text");
        //}

        //Fetch all user type related to Channel
        //public JsonResult GetUserTypeByChannelCode(string SEL_CHANNEL_CODE)
        //{
        //    string CHANNEL_CODE = GetChannelCode(SEL_CHANNEL_CODE);

        //    DataTable dtUserType = new DataTable();
        //    dtUserType = objChnl.GET_USER_TYPE_FOR_MENU_MAPPING(CHANNEL_CODE).Tables[0].DefaultView.ToTable(true, new string[] { "CHANNEL_USER_TYPE_ID", "USER_TYPE" });

        //    var results = from row in dtUserType.AsEnumerable()
        //                  select new
        //                  {
        //                      Value = row.Field<Int32>("CHANNEL_USER_TYPE_ID"),
        //                      Text = row.Field<string>("USER_TYPE")
        //                  };
        //    return Json(new SelectList(results, "Value", "Text"));
        //}

        //Get Channel Code by Login User
        private string GetChannelCode(string SEL_CHANNEL_CODE)
        {
            string CHANNEL_CODE;

            //If 'HO' or 'Admin' login then all Channel will dislpay else it will take from session
            string USER_TYPE = ((System.Data.DataTable)Session["UserDetails"]).Rows[0]["USER_TYPE"].ToString().ToUpper();
            if (USER_TYPE == "HO" || USER_TYPE == "ADMIN")
                CHANNEL_CODE = SEL_CHANNEL_CODE;
            else
                CHANNEL_CODE = ((System.Data.DataTable)Session["UserDetails"]).Rows[0]["CHANNEL_CODE"].ToString();
            return CHANNEL_CODE;
        }

        //Bind Menu Table on Channel DDL change
        public JsonResult GetBindGridForMenu(string SEL_CHANNEL_CODE, string SEL_USER_TYPE)
        {
            ArbabTravelsERP.Models.MENU objMenu = new ArbabTravelsERP.Models.MENU();
            DataTable dtUserType = new DataTable();
            dtUserType = objMenu_DAL.DislpayAppliedMenuList(SEL_CHANNEL_CODE, SEL_USER_TYPE);

            var result = from s in dtUserType.AsEnumerable()
                         select new
                         {
                             Menu_ID = s.Field<Int32>("Menu_ID"),
                             MENU_NAME = s.Field<string>("MENU_NAME"),
                             MENU_TITLE = s.Field<string>("MENU_TITLE"),
                             MENU_URL = s.Field<string>("PAGE_URL"),
                             IS_PARENT = s.Field<bool>("IS_PARENT"),
                             USER_TYPE_MENU_ID = s.Field<Int32>("USER_TYPE_MENU_ID")
                         };
            //select s;

            if (result.ToList().Count > 0)
                return Json(result, JsonRequestBehavior.AllowGet);
            else
                return Json("", JsonRequestBehavior.AllowGet);
        }
        #endregion
    }
}
